import React, { useEffect, useState } from "react";
import { Table, Button, Input, Space, Popconfirm, message, Tag, Select } from "antd";
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, CheckCircleOutlined, CloseCircleOutlined } from "@ant-design/icons";
import { addPostApi, getPostListApi, deletePostApi, approvePostApi, rejectPostApi, getPostApi, updatePostApi } from "@/apis/article";
import { uploadApi } from "@/apis/upload";
import Post from "@/components/post";
import PostView from "@/components/post/View";
import PostEdit from "@/components/post/Edit";
import { formatDateTime } from "@/utils/timeFormat";
import { useSelector } from "react-redux";

// import { getArticleListApi, deleteArticleApi, updateArticleStatusApi } from "@/apis/article";

const { Search } = Input;
const { Option } = Select;

const statusMap: Record<"pending" | "approved" | "rejected", { color: string; text: string }> = {
  pending: { color: "orange", text: "待审核" },
  approved: { color: "green", text: "已通过" },
  rejected: { color: "red", text: "已拒绝" },
};

const ArticleManage: React.FC = () => {
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState("");
  const [status, setStatus] = useState<string | undefined>(undefined);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  // 新建文章弹窗相关状态
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [post, setPost] = useState({ title: "", content: "", cover: "", userId: 0 });
  const [modalLoading, setModalLoading] = useState(false);
  const [viewOpen, setViewOpen] = useState(false);
  const [viewPost, setViewPost] = useState<any>({});
  const [editOpen, setEditOpen] = useState(false);
  const [editPost, setEditPost] = useState<any>({});
  const [editLoading, setEditLoading] = useState(false);
  const userId = useSelector((state: any) => state.user.profile?.ID);

  // 获取文章列表
  const fetchData = async (params = {}) => {
    setLoading(true);
    try {
      const res: any = await getPostListApi({
        ...params,
        search,
        status,
        page: pagination.current,
        pageSize: pagination.pageSize,
      });
      if (res.code === 0) {
        setData(res.data.list || res.data || []);
        setPagination(p => ({ ...p, total: res.data.total || (res.data.list ? res.data.list.length : 0) }));
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line
  }, [search, status, pagination.current, pagination.pageSize]);

  // 删除文章
  const handleDelete = async (ID: number) => {
    try {
      await deletePostApi(ID);
      message.success("删除成功");
      fetchData();
    } catch {
      message.error("删除失败");
    }
  };

  // 审核通过
  const handleApprove = async (ID: number) => {
    try {
      await approvePostApi(ID);
      message.success("已通过审核");
      fetchData();
    } catch {
      message.error("操作失败");
    }
  };

  // 审核拒绝
  const handleReject = async (ID: number) => {
    try {
      await rejectPostApi(ID);
      message.success("已拒绝");
      fetchData();
    } catch {
      message.error("操作失败");
    }
  };

  // 编辑/查看
  const handleEdit = async (ID: number) => {
    try {
      const res: any = await getPostApi(ID);
      if (res.code === 0) {
        const raw = res.data[0] || res.data;
        // 字段映射，确保小写
        const post = {
          ID: raw.ID,
          title: raw.title || raw.Title || "",
          content: raw.content || raw.Content || "",
          cover: raw.cover || raw.Cover || "",
        };
        setEditPost(post);
        setEditOpen(true);
      } else {
        message.error("获取文章详情失败");
      }
    } catch {
      message.error("获取文章详情失败");
    }
  };

  const handleEditOk = async (data: any) => {
    setEditLoading(true);
    try {
      await updatePostApi(data.ID, data);
      message.success("编辑成功");
      setEditOpen(false);
      fetchData();
    } catch {
      message.error("编辑失败");
    } finally {
      setEditLoading(false);
    }
  };

  const handleView = async (ID: number) => {
    try {
      const res: any = await getPostApi(ID);
      if (res.code === 0) {
        setViewPost(res.data);
        setViewOpen(true);
      } else {
        message.error("获取文章详情失败");
      }
    } catch {
      message.error("获取文章详情失败");
    }
  };

  const handleAddArticle = () => {
    setPost({ title: "", content: "", cover: "", userId: userId });
    setIsModalOpen(true);
  };

  const handleModalOk = async () => {
    setModalLoading(true);
    try {
      const res: any = await addPostApi({ ...post, UserID: userId });
      if (res.code === 0) {
        message.success("发帖成功");
        setIsModalOpen(false);
        fetchData();
      } else {
        message.error(res.message || "发帖失败");
      }
    } catch {
      message.error("请求失败");
    } finally {
      setModalLoading(false);
    }
  };

  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      render: (text: string, record: any) => (
        <a onClick={() => handleView(record.ID)}>{text}</a>
      ),
    },
    {
      title: "作者",
      dataIndex: "author",
      key: "author",
    },
    {
      title: "发布时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (_: any, record: any) => formatDateTime(record),
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => <Tag color={statusMap[status as keyof typeof statusMap]?.color}>{statusMap[status as keyof typeof statusMap]?.text}</Tag>,
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, record: any) => (
        <Space>
          <Button icon={<EyeOutlined />} size="small" onClick={() => handleView(record.ID)}>
            查看
          </Button>
          {record.userId === userId && (
            <Button icon={<EditOutlined />} size="small" onClick={() => handleEdit(record.ID)}>
              编辑
            </Button>
          )}
          <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.ID)}>
            <Button icon={<DeleteOutlined />} size="small" danger>
              删除
            </Button>
          </Popconfirm>
          {record.status === "pending" && (
            <>
              <Button icon={<CheckCircleOutlined />} size="small" type="primary" onClick={() => handleApprove(record.ID)}>
                通过
              </Button>
              <Button icon={<CloseCircleOutlined />} size="small" danger onClick={() => handleReject(record.ID)}>
                拒绝
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAddArticle}>新建文章</Button>
        <Search
          placeholder="搜索标题或作者"
          onSearch={value => { setSearch(value); setPagination(p => ({ ...p, current: 1 })); }}
          style={{ width: 200 }}
          allowClear
        />
        <Select
          placeholder="筛选状态"
          allowClear
          style={{ width: 120 }}
          onChange={value => { setStatus(value); setPagination(p => ({ ...p, current: 1 })); }}
        >
          <Option value="pending">待审核</Option>
          <Option value="approved">已通过</Option>
          <Option value="rejected">已拒绝</Option>
        </Select>
      </Space>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="ID"
        loading={loading}
        pagination={{
          ...pagination,
          onChange: (current, pageSize) => setPagination(p => ({ ...p, current, pageSize })),
        }}
      />
      <Post
        open={isModalOpen}
        onCancel={() => setIsModalOpen(false)}
        onOk={handleModalOk}
        confirmLoading={modalLoading}
        post={post}
        setPost={setPost}
        uploadApi={uploadApi}
      />
      <PostView open={viewOpen} onClose={() => setViewOpen(false)} post={viewPost} />
      <PostEdit
        open={editOpen}
        onClose={() => setEditOpen(false)}
        onOk={handleEditOk}
        confirmLoading={editLoading}
        post={editPost}
        setPost={setEditPost}
        uploadApi={uploadApi}
      />
    </div>
  );
};

export default ArticleManage;
